package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.YjhApplication;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.UrlAddress;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;

/**
 * Created by william_sun on 2016-08-10.
 * Description:webview的文章详情
 */
public class ArticleDetailActivity extends BaseActivity implements View.OnClickListener {

    private static int RESULT_COMMENT_ID = 1;
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private TextView tv_collect;
    private ImageView iv_title_func;

    private WebView webView;
    private ProgressBar pb_web;

    private String articleId;
    private String acctType = YjhApplication.articlekind_course;//0资讯 1课堂文章
    private String name;
    // [170515] 要跳转的评论
    private String commentId;

    private String kindTitle;

    private String isFromCollection="";
    private boolean isSelect = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_articledetail);

        articleId = getIntent().getStringExtra("articleId");
      //  Log.i("--articleId->>","articleId:"+articleId);
        acctType = getIntent().getStringExtra("acctType");
       // Log.i("--articleId->>","acctType:"+acctType);
        name = getIntent().getStringExtra("name");
        commentId = getIntent().getStringExtra("commentId");
        kindTitle = getIntent().getStringExtra("kindTitle");
        if (getIntent().hasExtra("kindName")){
            if (!TextUtils.isEmpty(getIntent().getStringExtra("kindName"))){
                kindTitle = getIntent().getStringExtra("kindName");
            }
        }
        if (getIntent().hasExtra("type")){
            acctType = getIntent().getStringExtra("type");
        }
        if(getIntent().hasExtra("isFromCollection")){
            isFromCollection = getIntent().getStringExtra("isFromCollection");
        }
      //  Log.i("--articleId->>","isFromColllection:"+isFromCollection);

        initView();
    }

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_COLLECTARTICALINFO_SUCCESS:
                if (msg.obj != null) {
                    if (!isSelect){
                        iv_title_func.setImageResource(R.drawable.icon_no_collection);
                    }else {
                        iv_title_func.setImageResource(R.drawable.icon_collection);
                    }
                    toastMsg(msg.obj.toString());

                } else {
                    toastMsg(R.string.collect_success);
                }
                break;
            case MessageCode.NETWORKCODE_COLLECTARTICALINFO_FAILURE:
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                } else {
                    toastMsg(R.string.collect_fail);
                }
                break;
            case MessageCode.NETWORKCODE_ARTICALISCOLLECT_SUCCESS:
                if (msg.obj!=null){
                   // Log.i("---msg--->",msg.obj.toString());
                    if (msg.obj.toString().equals("收藏")){
                        iv_title_func.setImageResource(R.drawable.icon_no_collection);
                        isSelect = false;
                    }else {
                       iv_title_func.setImageResource(R.drawable.icon_collection);
                        isSelect = true;
                    }

                }
                break;
            case MessageCode.NETWORKCODE_ARTICALISCOLLECT_FAILURE:

                break;

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_COMMENT_ID) {
            if (resultCode == RESULT_OK)
            {
                commentId = data.getStringExtra("commentId");
                // 重新加载一下文章
                String url = UrlAddress.H5_ARTICLEINFO_URL + "&articleId=" + articleId + "&acctType=" + loginInfo.getUserStyle() + "&userId=" + loginInfo.getUserId()+"&flag=app";
                if (commentId != null)
                {
                    url = url + "&pid=" + commentId;
                }
                webView.loadUrl(url);
            }
        }
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        tv_collect = (TextView) findViewById(R.id.tv_title_func);
        iv_title_func = (ImageView) findViewById(R.id.iv_title_func);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        iv_back.setOnClickListener(this);
        tv_title.setText(kindTitle);
//        tv_collect.setVisibility(View.VISIBLE);
        iv_title_func.setVisibility(View.VISIBLE);
        if("true".equals(isFromCollection)){
//            tv_collect.setText(getResources().getText(R.string.cancel_collect));
            iv_title_func.setImageResource(R.drawable.icon_collection);
            isSelect = true;
        }else{
            iv_title_func.setImageResource(R.drawable.icon_no_collection);
            isSelect = false;
//            tv_collect.setText(getResources().getText(R.string.newsdetail_text_collect));
        }
        iv_title_func.setOnClickListener(this);
//        tv_collect.setOnClickListener(this);

        if (loginInfo.getUserStyle().equals(YjhApplication.userstyle_nurse)) {
            tv_collect.setVisibility(View.INVISIBLE);
        }

        webView = (WebView) findViewById(R.id.webview_article);
        pb_web = (ProgressBar) findViewById(R.id.pb_article);

        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true); //支持js
        webSettings.setUseWideViewPort(true);  //将图片调整到适合webview的大小
        webSettings.setSupportZoom(true);  //支持缩放
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);  //设置缓存模式
        webSettings.setDomStorageEnabled(true);

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
//                Log.i(".....sfdsf...>",url);
                if (url.contains("comment_article")) {
                    Intent iComment = new Intent(mContext, CommentActivity.class);
                    iComment.putExtra("articleId", articleId);
                    iComment.putExtra("acctType", acctType);
                    startActivityForResult(iComment, RESULT_COMMENT_ID);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
//                super.onReceivedError(view, request, error);
                Message message= handlers.obtainMessage();
                message.what = 1000;
                handlers.sendMessage(message);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                pb_web.setProgress(newProgress);
                if (newProgress == 100) {
                    pb_web.setVisibility(View.INVISIBLE);
                }
                super.onProgressChanged(view, newProgress);
            }

        });

        String url = UrlAddress.H5_ARTICLEINFO_URL + "&articleId=" + articleId + "&acctType=" + loginInfo.getUserStyle() + "&userId=" + loginInfo.getUserId()+"&flag=app";
        if (commentId != null)
        {
            url = url + "&pid=" + commentId;
        }
       // Log.i("--------url-->","url:"+url.toString());
        webView.loadUrl(url);

    }
    protected Handler handlers = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1000:
//                    webView.loadUrl();
                   // toastMsg("加载自定义html");
                    break;
            }
        }
    };
    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onResume() {
        super.onResume();
        initView();
        YiJiaHuNetWorkUtils.ArticalIsCollect(articleId,acctType,handler);
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        webView.loadData("<a></a>", "text/html", "utf-8");
        super.onPause();
    }


        @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_title_func:
                loading();
                //收藏    0收藏1取消收藏
                if(isSelect){
                    isSelect = false;
                    YiJiaHuNetWorkUtils.collectArtical(articleId, "1", acctType + "", handler);
                }else{
                    Log.i("--articleId->>","收藏acctTye:"+acctType);
                    isSelect = true;
                    YiJiaHuNetWorkUtils.collectArtical(articleId, "0", acctType + "", handler);
                }
                break;
        }
    }
}
